package com.huike.report.service.impl;

import com.huike.business.mapper.TbBusinessMapper;
import com.huike.clues.domain.TbActivity;
import com.huike.clues.domain.TbAssignRecord;
import com.huike.clues.domain.TbClue;
import com.huike.clues.domain.vo.IndexStatisticsVo;
import com.huike.clues.mapper.*;
import com.huike.common.core.domain.entity.SysDept;
import com.huike.common.core.domain.entity.SysDictData;
import com.huike.common.utils.SecurityUtils;
import com.huike.contract.domain.TbContract;
import com.huike.contract.mapper.TbContractMapper;
import com.huike.report.domain.vo.*;
import com.huike.report.mapper.ReportMapper;
import com.huike.report.service.IReportService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class ReportServiceImpl implements IReportService {

    @Autowired
    private TbContractMapper contractMapper;


    @Autowired
    private SysDictDataMapper sysDictDataMapper;


    @Autowired
    private TbClueMapper clueMapper;

    @Autowired
    private TbActivityMapper activityMapper;


    @Autowired
    private SysDeptMapper deptMapper;

    @Autowired
    private TbAssignRecordMapper assignRecordMapper;
    
    @Autowired
    private ReportMapper reportMpper;

    @Autowired
    private TbBusinessMapper businessMapper;



    /**
     * 渠道统计
     */
    @Override
    public List<Map<String, Object>> chanelStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.chanelStatistics(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue= (String) datum.get("channel");
            String lable=  sysDictDataMapper.selectDictLabel("clues_item",subjectValue);
            datum.put("channel",lable);
        }
        return data;
    }

    @Override
    public IndexCluesVo cluesStatistics(String beginCreateTime, String endCreateTime) {
        IndexCluesVo indexCluesVo = new IndexCluesVo();
        try {
            List<String> dateList = findDates(beginCreateTime, endCreateTime);
            indexCluesVo.setXAxis(dateList);
            StatisticsVo statisticsVo1 = new StatisticsVo();
            statisticsVo1.setName("新增线索数量");
            StatisticsVo statisticsVo2 = new StatisticsVo();
            statisticsVo2.setName("线索总数量");
            List<StatisticsVo> series = new ArrayList<>();
            List<Map<String, Object>> dataMap= contractMapper.cluesStatistics(beginCreateTime,endCreateTime);
            int sun =0;
            for (String s : dateList) {
                    boolean falg= false;
                    for (Map<String, Object> stringObjectMap : dataMap) {
                        if (stringObjectMap.get("dd").equals(s)) {
                            statisticsVo1.getData().add(stringObjectMap.get("num"));
                            sun += Integer.parseInt(stringObjectMap.get("num").toString());
                            falg= true;
                            break;
                        }
                    }
                    if (!falg){
                        statisticsVo1.getData().add(0);
                    }
                statisticsVo2.getData().add(sun);

            }
            series.add(statisticsVo1);
            series.add(statisticsVo2);
            indexCluesVo.setSeries(series);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        /*StatisticsVo statisticsVo1 = new StatisticsVo();
        statisticsVo1.setName("新增线索数量");
        StatisticsVo statisticsVo2 = new StatisticsVo();
        statisticsVo2.setName("线索总数量");
        List<Map<String, Object>> data= contractMapper.cluesStatistics(beginCreateTime,endCreateTime);
        ArrayList strings = new ArrayList<>();
        ArrayList strings2 = new ArrayList<>();
        ArrayList strings3 = new ArrayList<>();

        for (Map<String, Object> datum : data) {
            strings.add(datum.get("dd"));

            strings2.add( datum.get("num"));
            strings3.add( datum.get("cum"));
        }

        Collections.reverse(strings);
        Collections.reverse(strings2);
        Collections.reverse(strings3);

        statisticsVo1.setData(strings2);
        statisticsVo2.setData(strings3);

        ArrayList<StatisticsVo> strings4 = new ArrayList<>();
        strings4.add(statisticsVo1);
        strings4.add(statisticsVo2);

        IndexCluesVo indexCluesVo = new IndexCluesVo(strings,strings4);*/

        return indexCluesVo;
    }

    @Override
    public IndexCluesVo contractStatistics(String beginCreateTime, String endCreateTime) {
        IndexCluesVo indexCluesVo = new IndexCluesVo();
        try {
            List<String> dates = findDates(beginCreateTime, endCreateTime);
            indexCluesVo.setXAxis(dates);
            List<StatisticsVo> series = new ArrayList<>();
            List<Map<String,Object>>  statistics = contractMapper.contractStatistics(beginCreateTime,endCreateTime);
            StatisticsVo lineSeriesDTO1=new StatisticsVo();
            lineSeriesDTO1.setName("新增客户数");
            StatisticsVo lineSeriesDTO2=new StatisticsVo();
            lineSeriesDTO2.setName("客户总数");
            int sum = 0;
            for (String s : dates) {
                Optional optional=  statistics.stream().filter(d->d.get("dd").equals(s)).findFirst();
                if(optional.isPresent()){
                    Map<String,Object> cuurentData=  (Map<String,Object>)optional.get();
                    lineSeriesDTO1.getData().add(cuurentData.get("num"));
                    sum += Integer.parseInt(cuurentData.get("num").toString());
                }else{
                    lineSeriesDTO1.getData().add(0);
                }
                lineSeriesDTO2.getData().add(sum);
            }
            series.add(lineSeriesDTO1);
            series.add(lineSeriesDTO2);
            indexCluesVo.setSeries(series);
        } catch (ParseException e) {
            e.printStackTrace();
        }


        return indexCluesVo;
    }

    @Override
    public IndexCluesVo salesStatistics(String beginCreateTime, String endCreateTime) {
        IndexCluesVo indexCluesVo = new IndexCluesVo();
        try {
            List<String> dates = findDates(beginCreateTime, endCreateTime);
            indexCluesVo.setXAxis(dates);
            List<StatisticsVo> series = new ArrayList<>();
            List<Map<String,Object>>  statistics = contractMapper.salesStatistics(beginCreateTime,endCreateTime);
            StatisticsVo lineSeriesDTO1=new StatisticsVo();
            lineSeriesDTO1.setName("销售统计");

            for (String s : dates) {
                Optional optional=  statistics.stream().filter(d->d.get("dd").equals(s)).findFirst();
                if(optional.isPresent()){
                    Map<String,Object> cuurentData=  (Map<String,Object>)optional.get();
                    lineSeriesDTO1.getData().add(cuurentData.get("sales"));
                }else{
                    lineSeriesDTO1.getData().add(0);
                }

            }
            series.add(lineSeriesDTO1);

            indexCluesVo.setSeries(series);
        } catch (ParseException e) {
            e.printStackTrace();
        }


        return indexCluesVo;
    }

    @Override
    public VulnerabilityVo getVulnerabilityMap(String beginCreateTime, String endCreateTime) {
        VulnerabilityVo result = new VulnerabilityVo();

        //线索数量
        result.setCluesNums(contractMapper.getCluesNums(beginCreateTime, endCreateTime));
        //有效线索数
        result.setEffectiveCluesNums(contractMapper.getEffectiveCluesNums(beginCreateTime, endCreateTime));
        //商机数量
        result.setBusinessNums(contractMapper.getBusinessNums(beginCreateTime, endCreateTime));
        //合同数量
        result.setContractNums(contractMapper.getContractNums(beginCreateTime, endCreateTime));
        return result;
    }

    @Override
    public List<Map<String, Object>> businessChangeStatistics(String beginCreateTime, String endCreateTime) {
        Integer allBusiness=  businessMapper.countAllBusiness(beginCreateTime,endCreateTime);
        List<Map<String,Object>> list= businessMapper.countAllContractByUser(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : list) {
            Long num= (Long) datum.get("num");
            datum.put("radio",getRadio(allBusiness,num));
        }
        return list;
    }

    @Override
    public List<Map<String, Object>> salesStatistic(String beginCreateTime, String endCreateTime) {
        Integer allBusiness=  clueMapper.countAllBusiness(beginCreateTime,endCreateTime);
        List<Map<String,Object>> list= clueMapper.countAllByUser(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : list) {
            Long num= (Long) datum.get("num");
            datum.put("radio",getRadio(allBusiness,num));
        }
        return list;
    }



    private BigDecimal getRadio(Integer all,Long num) {
        if(all.intValue()==0){
            return new BigDecimal(0);
        }
        BigDecimal numBigDecimal = new BigDecimal(num);
        BigDecimal allBigDecimal = new BigDecimal(all);
        BigDecimal divide = numBigDecimal.divide(allBigDecimal,4,BigDecimal.ROUND_HALF_UP);
        return divide.multiply(new BigDecimal(100));
    }

    @Override
    public List<TbContract> contractReportList(TbContract tbContract) {
       return contractMapper.selectTbContractList(tbContract);
    }


    @Override
    public List<Map<String, Object>> activityStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.activityStatistics(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : data) {
            Long activityId= (Long) datum.get("activity_id");
            TbActivity tbActivity = activityMapper.selectTbActivityById(activityId);
            if(tbActivity==null){
                datum.put("activity", "其他");
            }else{
                datum.put("activity", tbActivity.getName());
            }
        }
        return data;
    }

    /**
     * 统计分析-客户统计-学科客户分布饼图
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> subjectStatistics(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.subjectStatistics(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : data) {
            String subject= (String) datum.get("subject");
            SysDictData tbActivity = sysDictDataMapper.selectTbActivityById(subject);
            if(tbActivity==null){
                datum.put("subject", "其他");
            }else{
                datum.put("subject", tbActivity.getDictLabel());
            }
        }
        return data;
    }

    /**
     * 按照部门统计销售
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> deptStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.deptStatistics(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : data) {
            Long deptId= (Long) datum.get("dept_id");
            if(deptId!=null){
                SysDept dept= deptMapper.selectDeptById(deptId);
                datum.put("deptName", dept.getDeptName());
            }
        }
        return data;
    }


    /**
     * 按照渠道统计销售
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> channelStatisticsList(String beginCreateTime, String endCreateTime) {
        List<Map<String, Object>> data= contractMapper.channelStatistics(beginCreateTime,endCreateTime);
        for (Map<String, Object> datum : data) {
            String subjectValue= (String) datum.get("channel");
            if(subjectValue!=null){
                String lable=  sysDictDataMapper.selectDictLabel("clues_item",subjectValue);
                datum.put("channel",lable);
            }
        }
        return data;
    }


    /**
     * 按照归属人统计销售
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public List<Map<String, Object>> ownerShipStatisticsList(String beginCreateTime, String endCreateTime) {
       return  contractMapper.ownerShipStatistics(beginCreateTime,endCreateTime);
    }


    @Override
    public List<TbClue> cluesStatisticsList(TbClue clue) {
        return clueMapper.selectTbClueForReport(clue);
    }

    @Override
    public List<ActivityStatisticsVo> activityStatisticsList(TbActivity query) {
        query.setStatus("2");
        List<TbActivity> activities= activityMapper.selectTbActivityList(query);
        Map<String, Object> timeMap = query.getParams();
        List<ActivityStatisticsVo> list=new ArrayList<>();
        for (TbActivity activity : activities) {
            ActivityStatisticsVo dto = new ActivityStatisticsVo();
            BeanUtils.copyProperties(activity, dto);
            TbClue tbClue = new TbClue();
            tbClue.setActivityId(activity.getId());
            tbClue.setChannel(activity.getChannel());
            tbClue.setParams(timeMap);
            Map<String, Object> clueCount = clueMapper.countByActivity(tbClue);
            if (clueCount != null) {
                dto.setCluesNum(Integer.parseInt(clueCount.get("total").toString()));
                if(clueCount.get("falseClues")!=null){
                    dto.setFalseCluesNum(Integer.parseInt(clueCount.get("falseClues").toString()));
                }
                if (clueCount.get("toBusiness") != null) {
                    dto.setBusinessNum(Integer.parseInt(clueCount.get("toBusiness").toString()));
                }
            }
            TbContract tbContract = new TbContract();
            tbContract.setChannel(activity.getChannel());
            tbContract.setActivityId(activity.getId());
            tbContract.setParams(timeMap);
            Map<String, Object> contractCount = contractMapper.countByActivity(tbContract);
            if (contractCount != null) {
                dto.setCustomersNum(Integer.parseInt(contractCount.get("customersNum").toString()));
                if(contractCount.get("amount")==null) {
                	dto.setAmount(0d);
                }else {
                	dto.setAmount((Double) contractCount.get("amount"));
                }
                if(contractCount.get("cost")==null) {
                	dto.setCost(0d);
                }else {
                	dto.setCost((Double) contractCount.get("cost"));
                }
                
            }
            list.add(dto);
        }
        return list;
    }


    @Override
    public IndexVo getIndex(IndexStatisticsVo request) {
        Long deptId= request.getDeptId();
        TbAssignRecord tbAssignRecord=new TbAssignRecord();
        tbAssignRecord.setLatest("1");
        assignRecordMapper.selectAssignRecordList(tbAssignRecord);
        return null;
    }


    /**
     * 获取首页基本数据
     * @param beginCreateTime
     * @param endCreateTime
     * @return
     */
    @Override
    public IndexBaseInfoVO getBaseInfo(String beginCreateTime, String endCreateTime) {
        //1 构建一个空的结果集对象
        IndexBaseInfoVO result = new IndexBaseInfoVO();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();
        // 2.2 开始查询第一个属性 线索数量
        result.setCluesNum(reportMpper.getCluesNum(beginCreateTime, endCreateTime, username));
        // 2.3 开始查询第一个属性 商机数量
        result.setBusinessNum(reportMpper.getBusinessNum(beginCreateTime, endCreateTime, username));
        // 2.4 开始查询第一个属性 合同数量
        result.setContractNum(reportMpper.getContractNum(beginCreateTime, endCreateTime, username));
        // 2.5 开始查询第一个属性 销售金额数量
        result.setSalesAmount(reportMpper.getSalesAmount(beginCreateTime, endCreateTime, username));
        //5 返回结果集对象
        return result;
    }

    @Override
    public IndexTodayInfoVo getTodayInfo(String nowDate) {
        //1 构建一个空的结果集对象
        IndexTodayInfoVo result = new IndexTodayInfoVo();
        //2 封装结果集属性
        // 2.1 由于查询需要用到用户名 调用工具类获取用户名
        String username = SecurityUtils.getUsername();
        // 2.2 开始查询第一个属性 线索数量
        result.setTodayCluesNum(reportMpper.getTodayCluesNum( username,nowDate));
        // 2.3 开始查询第一个属性 商机数量
        result.setTodayBusinessNum(reportMpper.getTodayBusinessNum( username,nowDate));
        // 2.4 开始查询第一个属性 合同数量
        result.setTodayContractNum(reportMpper.getTodayContractNum( username,nowDate));
        // 2.5 开始查询第一个属性 销售金额数量
        result.setTodaySalesAmount(reportMpper.getTodaySalesAmount(username,nowDate));
        //5 返回结果集对象
        return result;
    }

    @Override
    public IndexTodoInfoVo getTodoInfo(String beginCreateTime, String endCreateTime) {
        IndexTodoInfoVo result = new IndexTodoInfoVo();

        result.setTofollowedCluesNum(reportMpper.getTofollowedCluesNum(beginCreateTime, endCreateTime));
        result.setTofollowedBusinessNum(reportMpper.getTofollowedBusinessNum(beginCreateTime, endCreateTime));
        result.setToallocatedCluesNum(reportMpper.getToallocatedCluesNum(beginCreateTime, endCreateTime));
        result.setToallocatedBusinessNum(reportMpper.getToallocatedBusinessNum(beginCreateTime, endCreateTime));
        return result;

    }

    public static List<String> findDates(String beginTime, String endTime) throws ParseException {
        List<String> allDate = new ArrayList();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        Date dBegin = sdf.parse(beginTime);
        Date dEnd = sdf.parse(endTime);
        allDate.add(sdf.format(dBegin));
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则，为给定的日历字段添加或减去指定的时间量
            calBegin.add(Calendar.DAY_OF_MONTH, 1);
            allDate.add(sdf.format(calBegin.getTime()));
        }
        System.out.println("时间==" + allDate);
        return allDate;
    }


}